<template>
  <div>
    <h1>Knowledge Points</h1>
    <div v-if="categories.length > 0">
      <div v-for="category in categories" :key="category" class="category-section">
        <h2>{{ capitalize(category) }}</h2>
        <div v-for="type in types" :key="type" class="type-section">
          <h3>{{ typeTitles[type] }}</h3>
          <div v-if="groupedKnowledgePoints[category][type].length > 0">
            <div v-for="item in groupedKnowledgePoints[category][type]" :key="item.id">
              <el-link :type="type" @click="goToDetail(item.id, item.category)">
                {{ item.title }}
              </el-link>
            </div>
          </div>
          <div v-else>暂无</div>
        </div>
      </div>
    </div>
    <div v-else>
      <p>暂无知识点。</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useKnowledgeStore } from '@/stores/knowledge'

// 初始化路由和 store
const router = useRouter()
const store = useKnowledgeStore()

// 在组件挂载时加载知识点
onMounted(() => {
  store.loadKnowledgePoints() // 确保在页面加载时调用这个方法
})

// 获取所有知识点
const knowledgePoints = computed(() => store.knowledgePoints)

// 获取所有唯一的分类
const categories = computed(() => {
  const categorySet = new Set<string>()
  knowledgePoints.value.forEach((point) => {
    categorySet.add(point.category)
  })
  return Array.from(categorySet)
})

// 定义所有掌握程度类型
const types = ['danger', 'warning', 'success'] as const

// 定义掌握程度的中文标题
const typeTitles: Record<(typeof types)[number], string> = {
  danger: '不了解',
  warning: '一知半解',
  success: '懂了'
}

// 按分类和掌握程度分组知识点
const groupedKnowledgePoints = computed(() => {
  const groups: Record<string, Record<(typeof types)[number], typeof knowledgePoints.value>> = {}

  categories.value.forEach((category) => {
    groups[category] = {
      danger: [],
      warning: [],
      success: []
    }
  })

  knowledgePoints.value.forEach((point) => {
    if (groups[point.category]) {
      groups[point.category][point.type].push(point)
    } else {
      // 如果出现新的分类，初始化该分类
      groups[point.category] = {
        danger: [],
        warning: [],
        success: []
      }
      groups[point.category][point.type].push(point)
    }
  })

  return groups
})

// 跳转到详情页
const goToDetail = (id: string, category: string) => {
  router.push({ name: 'KnowledgeDetail', params: { category, id } })
}

// 辅助方法：将分类名称首字母大写
const capitalize = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
</script>

<style scoped>
.category-section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}
.type-section {
  margin-left: 20px;
  margin-bottom: 20px;
}
h2 {
  color: #409eff; /* Vue 3 蓝色 */
}
h3 {
  color: #67c23a; /* 成功绿色 */
}
</style>
